package com.nulldev.util.scripting.cup.vee.registers;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import com.nulldev.util.scripting.cup.vee.CUPRegister;

public class StringCUPRegister extends CUPRegister<String> {

	private final int registerID;

	public StringCUPRegister(final int registerID) {
		this.registerID = registerID;
	}

	private final AtomicReference<String> value = new AtomicReference<String>();
	private final AtomicBoolean lock = new AtomicBoolean();

	@Override
	public CUPRegisterType getRegisterType() {
		return CUPRegisterType.STRING;
	}

	@Override
	public void reset() {
		if (this.lock.get())
			return;
		this.value.set(null);
	}

	@Override
	public String get() {
		return this.value.get();
	}

	@Override
	public void set(String value) {
		if (this.lock.get())
			return;
		this.value.set(value);
	}

	@Override
	public boolean valuePresent() {
		return this.value.get() != null;
	}

	@Override
	public int getRegisterID() {
		return this.registerID;
	}

	@Override
	public CUPRegister<String> setAndReturn(final String value) {
		if (this.lock.get())
			return this;
		else
			return super.setAndReturn(value);
	}

	public StringCUPRegister lock() {
		this.lock.set(true);
		return this;
	}
}
